package com.vessel.decoration.mvp.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.jess.arms.di.component.AppComponent;
import com.jess.arms.utils.ArmsUtils;
import com.jess.arms.utils.DataHelper;
import com.jess.arms.utils.PermissionUtil;
import com.pgyersdk.crash.PgyCrashManager;
import com.pgyersdk.update.PgyUpdateManager;
import com.pgyersdk.update.UpdateManagerListener;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.tencent.bugly.crashreport.CrashReport;
import com.vessel.decoration.R;
import com.vessel.decoration.app.base.MySupport1Activity;
import com.vessel.decoration.di.component.DaggerMainComponent;
import com.vessel.decoration.di.module.MainModule;
import com.vessel.decoration.mvp.contract.MainContract;
import com.vessel.decoration.mvp.presenter.MainPresenter;
import com.vessel.decoration.mvp.ui.fragment.NavHomeFragment;
import com.vessel.decoration.mvp.ui.widget.SplashView;

import org.json.JSONException;
import org.json.JSONObject;

import static com.jess.arms.utils.Preconditions.checkNotNull;

/**
 * @author vesselzhang
 * @date 2017/11/25
 */

@Route(path = "/app/main")
public class MainActivity extends MySupport1Activity<MainPresenter> implements MainContract.View {

    private long time = 0;
    private static final int REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSIONS = 1;
    private static final int REQUEST_CODE_WRITE_EXTERNAL_STORAGE = 2;

    @Override
    public void setupActivityComponent(AppComponent appComponent) {
        DaggerMainComponent //如找不到该类,请编译一下项目
                .builder()
                .appComponent(appComponent)
                .mainModule(new MainModule(this))
                .build()
                .inject(this);
    }

    @Override
    public int initView(Bundle savedInstanceState) {
        return R.layout.activity_main;
    }

    @Override
    public void initData(Bundle savedInstanceState) {
        CrashReport.initCrashReport(getApplicationContext(), "99c2657abf", false);
        //动态请求权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            PermissionUtil.requestPermission(new PermissionUtil.RequestPermission() {
                                                 @Override
                                                 public void onRequestPermissionSuccess() {

                                                 }

                                                 @Override
                                                 public void onRequestPermissionFailure() {

                                                 }
                                             }, new RxPermissions(this), ArmsUtils.obtainAppComponentFromContext(this).rxErrorHandler(),
                    Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CALL_PHONE);
        }
        PgyCrashManager.register(this);
        PgyUpdateManager.register(this, new UpdateManagerListener() {
            @Override
            public void onNoUpdateAvailable() {
            }

            @Override
            public void onUpdateAvailable(String result) {
                String url = null;
                JSONObject jsonData;
                try {
                    jsonData = new JSONObject(result);
                    if ("0".equals(jsonData.getString("code"))) {
                        JSONObject jsonObject = jsonData.getJSONObject("data");
                        url = jsonObject.getString("downloadURL");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                if (TextUtils.isEmpty(url)) {
                    return;
                }
                if (!TextUtils.isEmpty(DataHelper.getStringSF(MainActivity.this, "url"))
                        && url.contains(DataHelper.getStringSF(MainActivity.this, "url"))) {
                    return;
                }
                String finalUrl = url;
                new AlertDialog.Builder(MainActivity.this)
                        .setTitle("发现新版本")
                        .setMessage("已有新版本，请点击更新")
                        .setPositiveButton("确定", (dialog, which) -> startDownloadTask(MainActivity.this, finalUrl))
                        .setNegativeButton("取消", (dialogInterface, i) -> {
                            int index = finalUrl.indexOf("?");
                            DataHelper.setStringSF(MainActivity.this, "url", finalUrl.substring(0, index - 1));
                        })
                        .show();
            }
        });
        mPresenter.getIndexInfo();
        //加载广告页
        showSplashView();
        initFragmentation();
        initNavigationView();

//        startService(new Intent(this, BackService.class));
    }

    @SuppressLint("NewApi")
    @Override
    public void onRequestPermissionsResult(int requestCode,
                                           String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_WRITE_EXTERNAL_STORAGE: {
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {


                    } else {
                    }

                }
            }
            case REQUEST_CODE_READ_EXTERNAL_STORAGE_PERMISSIONS: {
                for (int i = 0; i < permissions.length; i++) {
                    if (grantResults[i] == PackageManager.PERMISSION_GRANTED) {
//                        Toast.makeText(this, "权限允许", Toast.LENGTH_SHORT).show();
                    } else {
                        Toast.makeText(this, "权限被拒绝，可能会导致更新出错", Toast.LENGTH_SHORT).show();
                    }

                }
            }
            break;
            default: {
                super.onRequestPermissionsResult(requestCode, permissions,
                        grantResults);
            }
        }
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void showMessage(String message) {
        checkNotNull(message);
        ArmsUtils.snackbarText(message);
    }

    @Override
    public void launchActivity(Intent intent) {
        checkNotNull(intent);
        ArmsUtils.startActivity(intent);
    }

    @Override
    public void killMyself() {
        finish();
    }

    private void showSplashView() {
        SplashView.showSplashView(this, 2, R.drawable.splash, new SplashView.OnSplashViewActionListener() {
            @Override
            public void onSplashImageClick(String actionUrl) {
                Log.d("SplashView", "img clicked. actionUrl: " + actionUrl);
//                Toast.makeText(MainActivity.this, "img clicked.", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSplashViewDismiss(boolean initiativeDismiss) {
                Log.d("SplashView", "dismissed, initiativeDismiss: " + initiativeDismiss);
                initStatusBar(); //启动页面完毕后刷状态栏
            }
        });

//         call this method anywhere to update splash view data
//        SplashView.updateSplashData(this, "http://ww2.sinaimg.cn/large/72f96cbagw1f5mxjtl6htj20g00sg0vn.jpg", "http://jkyeo.com");
    }

    private void initFragmentation() {
        NavHomeFragment homeFragment = findFragment(NavHomeFragment.class);
        if (homeFragment == null) {
            loadRootFragment(R.id.fl_content, NavHomeFragment.newInstance());
        }
    }

//    private void initStatusBar() {
//        SystemBarHelper.tintStatusBarForDrawer(this, mDrawer, ArmsUtils.getColor(this, R.color.colorPrimary));
//        SystemBarHelper.setPadding(this, mNav.getHeaderView(0));
//        SystemBarHelper.setPadding(this, mLlRoot);
//    }

    private void initNavigationView() {
//        mNav.setBackgroundColor(ArmsUtils.getColor(this, R.color.nav_menu_bg));
//        removeNavigationViewScrollbar(mNav);
//        mNav.setCheckedItem(R.id.nav_home);
//        mNav.setNavigationItemSelectedListener(this);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (System.currentTimeMillis() - time > 1000) {
                Toast.makeText(this, "再按一次返回桌面", Toast.LENGTH_SHORT).show();
                time = System.currentTimeMillis();
            } else {
                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                startActivity(intent);
            }
            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }
}
